//
//  AppDelegate.m
//  AKPZ
//
//  Created by Lexi on 16-3-14.
//  Copyright (c) 2016年 aikangpeizhen. All rights reserved.
//

#import "AppDelegate.h"
#import "AFNetworking.h"
#import "AKClient.h"

void UncaughtExceptionHandler(NSException *exception) {
    
}

@interface AppDelegate ()

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [AKUserDefaults registerUserDefaults];
    [self initLaunchView];
    [self login];
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application {}

- (void)applicationDidEnterBackground:(UIApplication *)application {}

- (void)applicationWillEnterForeground:(UIApplication *)application {}

- (void)applicationDidBecomeActive:(UIApplication *)application {}

- (void)applicationWillTerminate:(UIApplication *)application {}

#pragma mark - Init

- (void)login {
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    if (IOS7) {
        [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
    } else {
        [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
    }
    self.loginVC = [StoryBoard(@"LoginAndRegist") instantiateViewControllerWithIdentifier:@"LoginVCSID"];
    [self.window setRootViewController:_loginVC];
    [self.window makeKeyAndVisible];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginSuccess) name:UserLoginNotification object:nil];
    
    //提前初始化主界面(抽屉), 但不显示
    [self initUI];
}

//直到登录成功以后才显示抽屉界面
- (void)loginSuccess {
    [UIView animateWithDuration:1.f animations:^{
        _loginVC.view.alpha = 0.f;
        [self.window setRootViewController:_drawerController];
    } completion:^(BOOL finished) {
        _loginVC.view.hidden = YES;
        [_loginVC.view removeFromSuperview];
        self.loginVC = nil;
    }];
}

- (void)initUI {
    DLog(@"========initUI");
    LeftDrawerVC *leftDrawerVC = [[LeftDrawerVC alloc] initWithNibName:@"LeftDrawerVC" bundle:nil];
    leftDrawerVC.delegate = self;
    //    leftSideDrawerViewController.view.backgroundColor = [UIColor clearColor];
    UIViewController *centerViewController = nil;
    self.indexVC = [StoryBoard(@"Index") instantiateViewControllerWithIdentifier:@"IndexVCSID"];
    centerViewController = _indexVC;
    UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:centerViewController];
    self.navController = navigationController;
    self.drawerController = [[MMDrawerController alloc] initWithCenterViewController:_navController
                                                            leftDrawerViewController:leftDrawerVC
                                                           rightDrawerViewController:nil];
    [_drawerController setMaximumLeftDrawerWidth:240.f];
    [_drawerController setMaximumRightDrawerWidth:240.f];
    [_drawerController setOpenDrawerGestureModeMask:MMOpenDrawerGestureModePanningNavigationBar| MMOpenDrawerGestureModePanningCenterView];
    [_drawerController setCloseDrawerGestureModeMask:MMCloseDrawerGestureModeAll];
    [_drawerController setShowsShadow:NO];
    [_drawerController setDrawerVisualStateBlock:[self moveAndScaleVisualStateBlock]];
}

- (void)initLaunchView {
    [self.window makeKeyAndVisible];
}

#pragma mark - LeftSideDrawer

- (void)leftSideDrawerViewDelegate:(LeftDrawerButton)btnType {
    MMDrawerController *mm = (MMDrawerController *)self.window.rootViewController;
    switch (btnType) {
        case LeftDrawerButton_Background: { //背景按钮
            break;
        }
        case LeftDrawerButton_Logout: { //注销
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"是否确认注销?"
                                                            message:@"注销当前登录用户后，将无法查看车辆管理信息"
                                                           delegate:self
                                                  cancelButtonTitle:@"取消"
                                                  otherButtonTitles:@"注销", nil];
            alert.tag = 101;
            [alert show];
            break;
        }
        case LeftDrawerButton_Index: { //首页
            UINavigationController *navtmp = (UINavigationController *)mm.centerViewController;
            UIViewController *vc = [navtmp.viewControllers objectAtIndex:0];
            if ([vc isKindOfClass:[_indexVC class]]) {
                [mm closeDrawerAnimated:YES completion:nil];
            } else {
                if (!_indexVC) {
                    self.indexVC = [StoryBoard(@"Index") instantiateViewControllerWithIdentifier:@"RegistNextVCSID"];
                }
                self.navController = [[UINavigationController alloc] initWithRootViewController:_indexVC];
                [mm setCenterViewController:_navController withCloseAnimation:YES completion:nil];
            }
            break;
        }
        case LeftDrawerButton_Settings: { //设置
            break;
        }
        case LeftDrawerButton_MsgCenter: { //消息中心
            break;
        }
        case LeftDrawerButton_Help: { //帮助
            break;
        }
        case LeftDrawerButton_CheckNew: { //检查新版本
            break;
        }
        case LeftDrawerButton_AboutUs: { //关于
            break;
        }
        default:
            break;
    }
}

- (MMDrawerControllerDrawerVisualStateBlock)moveAndScaleVisualStateBlock {
    MMDrawerControllerDrawerVisualStateBlock visualStateBlock =
    ^(MMDrawerController * drawerController, MMDrawerSide drawerSide, CGFloat percentVisible) {
        
        UIView *centerView = drawerController.centerViewController.view;
        CGFloat minScale = .80;
        CGFloat scale = minScale + ((1.0-percentVisible)*(1.0-minScale));
        
        CGFloat translateX = 0;//percentVisible * (40.);
        CGAffineTransform transT = CGAffineTransformMakeTranslation(translateX, 0);
        CGAffineTransform scaleT = CGAffineTransformMakeScale(scale, scale);
        CGAffineTransform conT = CGAffineTransformConcat(transT, scaleT);
        
        UIViewController * sideDrawerViewController = nil;
        if (drawerSide == MMDrawerSideLeft) {
            sideDrawerViewController = drawerController.leftDrawerViewController;
        }
        else if (drawerSide == MMDrawerSideRight) {
            sideDrawerViewController = drawerController.rightDrawerViewController;
        }
        
        CGRect rect = sideDrawerViewController.view.frame;
        rect.origin.x = (percentVisible-1.) * (0.6*rect.size.width);
        [sideDrawerViewController.view setFrame:rect];
        
        centerView.transform = conT;
        
    };
    return visualStateBlock;
}

- (UIViewController *)topController {
    MMDrawerController *drawer = (MMDrawerController *)self.window.rootViewController;
    UINavigationController *nav = (UINavigationController *)drawer.centerViewController;
    if (nav.viewControllers.count > 0) {
        UIViewController *controller = [nav.viewControllers lastObject];
        if (controller.presentedViewController != nil) {
            if ([controller.presentedViewController isKindOfClass:[UINavigationController class]]) {
                NSArray *controllers = [(UINavigationController *)controller.presentedViewController viewControllers];
                controller = [controllers lastObject];
            } else if ([controller.presentedViewController isKindOfClass:[UIViewController class]]) {
                controller = controller.presentedViewController;
            }
        }
        return controller;
    }
    return nil;
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    NSInteger tag = alertView.tag;
    if (tag == 101) {
        switch (buttonIndex) {
            case 0: {
                break;
            }
            case 1: {
                NSLog(@"注销");
                [[AKClient sharedInstance] setLoginInfo:nil];
                [[AKClient sharedInstance] setLogon:NO];
                [[NSNotificationCenter defaultCenter] postNotificationName:UserLogoutNotification object:nil];
                LoginVC *login = [StoryBoard(@"LoginAndRegist") instantiateViewControllerWithIdentifier:@"RegistNextVCSID"];
                [self.navController presentViewController:login animated:YES completion:nil];
                break;
            }
            default:
                break;
        }
    }
}

@end
